import { createRouter, createWebHashHistory } from 'vue-router'
import AIOHome from '@/views/AIOHome.vue'
import AIOLogin from "@/views/AIOLogin.vue";
import AIORegister from "@/views/AIORegister.vue";
import AIOPersonCenter from "@/views/AIOPersonCenter.vue";
import AIOChat from "@/views/AIOChat.vue";
import AIOArchive from "@/views/AIOArchive.vue";
import AIOPlayScript from "@/views/AIOPlayScript.vue";
import AIOAdmin from "@/views/AIOAdmin.vue";

const routes = [
    {
        path: '/',
        name: 'AIOHome',
        component: AIOHome
    },
    {
        path:'/AIOLogin',
        name:'AIOLogin',
        component: AIOLogin
    },
    {
        path:'/AIORegister',
        name:'AIORegister',
        component: AIORegister
    },
    {
        path:'/AIOPersonCenter',
        name:'AIOPersonCenter',
        component: AIOPersonCenter
    },
    {
        path: '/AIOChat/:scriptId/:conversationId',
        name: 'AIOChat',
        component: AIOChat
    },
    {
        path:'/AIOArchive',
        name:'AIOArchive',
        component: AIOArchive
    },
    {
        path:'/AIOPlayScript',
        name:'AIOPlayScript',
        component: AIOPlayScript
    },
    {
        path:'/AIOAdmin',
        name:'AIOAdmin',
        component: AIOAdmin
    },
    {
        path: '/AIOArchive',
        name:'AIOArchive',
        component: AIOArchive
    }
]

const router = createRouter({
    history: createWebHashHistory(),
    routes
})

const publicPages = ['/AIOHome', '/AIOLogin', '/AIORegister','/'];
const adminOnlyPages = ['/AIOAdmin'];

router.beforeEach((to, from, next) => {
    const isPublicPage = publicPages.includes(to.path);
    const isAdminPage = adminOnlyPages.includes(to.path);
    const isLoggedIn = localStorage.getItem('token');
    const userInfo = JSON.parse(localStorage.getItem('userInfo'));
    const userRole = userInfo ? userInfo.role : "user";

    // 检查是否未登录访问受限页面
    if (!isPublicPage && !isLoggedIn) {
        alert("请先登录！");
        next('/AIOLogin');
    }
    // 检查是否非管理员访问管理员页面
    else if (isAdminPage && userRole !== 'admin') {
        alert("无访问权限");
        next('/'); // 重定向到首页
    }
    else {
        next(); // 允许访问
    }
});


export default router